<?php
/**
* 功能: redis操作类
* 创建日期:Mon Apr 25 09:24:37 CST 2011
* 最后更新:
* 作者: slash
*/
class redisBase {
	/**
	 * 构造方法
	 *
	 * @return redis
	 */
	var $redis;
	function redisBase() {
		
	}
	
	function __construct()
	{
		if(class_exists("Redis")){
			$this->redis = new Redis();
		}
	}
	/**
	 * 链接服务器
	 *
	 * @param unknown_type 服务器地址
	 * @param unknown_type 端口
	 * @return unknown
	 */
	function setConnect($host,$port)
	{
		try{
		
			$this->redis->connect($host,$port);
			return $this->redis;
		}catch(Exception $e){
			return false;
		}


		/*
		if($this->redis->connect($host,$port)){
			return $this->redis;
			
		}else{
			echo "链接失败";
			return false;
		}
		*/
		
	}
	/**
	 * 设置内容	
	 *
	 * @param unknown_type $key 键值
	 * @param unknown_type $value 内容
	 * @param unknown_type $period 失效时间，不失效则为0
	 */
	function setValue($key,$value,$period=0)
	{
		$re = $this->redis->set($key,$value);
		if($period){
			$this->redis->expire($key,$period); 
		}
		return $re;
	}
	/**
	 * 获得内容
	 *
	 * @param unknown_type $key 键值
	 * @return unknown
	 */
	function getValue($key)
	{
		return $this->redis->get($key);
	}
	/**
	 * 设置列表模式
	 *
	 * @param unknown_type $list
	 * @param unknown_type $array
	 * @param unknown_type $period
	 * @return unknown
	 */
	function setList($list,$array,$period=0)
	{
		if(is_array($array)){
			foreach ($array as $k=>$v){
				if(!is_int($k)){
					return fasle;
				}
			}
			foreach ($array as $k=>$v){
				$re = $this->redis->rpush($list,serialize($v));
			}
		}else{
			$re = $this->redis->rpush($list,serialize($array));
		}
		
		if($period){
			$this->redis->expire($list,$period); 
		}
		return $re;
	}
	
	function getList($list,$start=0,$end=-1)
	{
		$arr = $this->redis->lrange($list,$start,$end);
		$new_array = array();
		if(is_array($arr)){
			foreach($arr as $k=>$v){
				$new_array[] = unserialize($v);
			}
		return $new_array;		
		}
		return false;
	}
	/**
	 * 修改LIST中KEY对应的值
	 *
	 * @param unknown_type $list
	 * @param unknown_type $key
	 * @return unknown
	 */
	function updateList($list,$key,$value='')
	{
		return $this->redis->lset($list,$key,$value);
	}
	
	function trimList($list,$start,$end)
	{
		return $this->redis->ltrim($list,$start,$end);
	}

	function dropList($list){
		$count = $this->redis->llen($list);
		if($count){
			for($i=0;$i<$count;$i++){
				$re = $this->redis->lpop($list);
			}
			return $re;
		}
	}
	/**
	 * 删除键值对应的值
	 *
	 * @param unknown_type $key 
	 * @return unknown
	 */
	function delValue($key)
	{
		return $this->redis->del($key);
	}
}
?>